// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;

namespace SnapObjects.Data
{
    internal abstract class SqlFunctionStatementParser : SqlStatementParser
    {
        public SqlFunctionStatementParser(
            ISqlStatementFactory factory, ISqlGenerationHelper helper) : base(factory, helper)
        {
        }

        public abstract SqlStatement Parse(string sqlText, FunctionReturnType returnType);

        public override SqlStatement ParseStatement(ISqlTokenizer tokenizer, bool isClause)
        {
            return this.ParseStatement(tokenizer, isClause, FunctionReturnType.Scalar);
        }

        public virtual SqlStatement ParseStatement(
            ISqlTokenizer tokenizer, bool isClause, FunctionReturnType returnType)
        {
            var statement = new SqlFunctionStatement(returnType);

            var procedureName = String.Empty;

            var endParseName = false;

            while (tokenizer.MoveNext())
            {
                if (tokenizer.Current.Type == SqlTokenType.Parameter &&
                    tokenizer.Current is SqlParameterToken parameter)
                {
                    statement.Parameters.Add(tokenizer.Current.Text, parameter);

                    endParseName = true;
                }
                else if (tokenizer.Current.Type != SqlTokenType.Whitespace && !endParseName)
                {
                    procedureName += tokenizer.Current.Text;
                }
            }

            if (!String.IsNullOrEmpty(procedureName))
            {
                statement.Function.Add(new SqlStringToken(procedureName));
            }
            else
            {
                statement = null;
            }

            return statement;
        }
    }
}
